﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using UFC.Common;
using System.Xml;
using UFC.DBUtility;
using System.Configuration;

namespace MESQualityHistoryRecord
{
    class SendQualityMentionToQms
    {
        public void RunQualityMentionSync()
        {
            DataTable mydt = GetQualityHistoryRecord();
            if (mydt == null || mydt.Rows.Count <= 0)
            {
                LogHelp.WriteLog("没有可处理的质量提起记录");
            }
          
            foreach (DataRow row in mydt.Rows) {
                var strList = GetDictionary(row);
                string resQxml = CreateXMLForQualityMentionToQms(strList);
                LogHelp.WriteLog("质量问题信息报告单接口-推送XMl:" + resQxml);
                NewMesToQms.unifiedFunApi mtq = new NewMesToQms.unifiedFunApi();
                var resPxml = mtq.mesToQmsAPI(resQxml);
                LogHelp.WriteLog("质量问题信息报告单接口-返回XMl:" + resPxml);
                Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                        {"ParentId",row["qualityhistoryrecordid"].ToString ()},{"RecordType","QMS_qaProblemInfoReport"},
                        {"ContainerID",""},{"ContainerName",row["productNum"].ToString()},
                        {"ProductName",row["productName"].ToString()},{"WorkflowStepName",row["problemOperation"].ToString()},
                        {"SendXml",resQxml},{"ResXml",resPxml}
                    };
                XmlDocument myxml = new XmlDocument();
                myxml.LoadXml(resPxml);
                string xml = myxml.SelectSingleNode("RespMsg/document").InnerText;
                myxml.LoadXml(xml);
                string success = myxml.SelectSingleNode("TETTYP/RTYPE").InnerText;//
                string message = myxml.SelectSingleNode("TETTYP/RTMSG").InnerText;//
                if (!string.IsNullOrWhiteSpace(success) && success == "S")
                {
                    recordPara.Add("IsSuccess", "0");//成功
                    //UpdateQualityHistoryRecord(row["orderNo"].ToString(), row["dealName"].ToString());
                }
                else
                {
                    recordPara.Add("IsSuccess", "1");//失败
                    LogHelp.WriteLog(message);
                }
                OracleDAL.InserOtherSystemRecord(recordPara);
            }
        }
        /// <summary>
        /// 获取质量提起数据
        /// </summary>
        /// <returns></returns>
        private DataTable GetQualityHistoryRecord()
        {
            try
            {
                string strSql = @"SELECT q.qualityhistoryrecordid,q.MFGORDERNAME orderNo,q.DEALNAME dealName,f.FACTORYNAME productionUnit,wf1.PRODUCTFAMILYNAME masterModel,w.WORKCENTERNAME occurrencePlace,to_char(q.createtime,'yyyy-MM-dd hh24:mm:ss') occurrenceDate
                                ,p2.DESCRIPTION productName,PRODUCTITEMNAME drawingNo,wf1.CONTAINERNO productNum, q.UNQUALIFIEDNUM occurrenceQuantity,q.UNQUALIFIEDDESCRIBE impactConsequence
                                ,w2.WORKFLOWSTEPNAME problemOperation,SUBSTR(w2.WORKFLOWSTEPNAME,0,INSTR(w2.WORKFLOWSTEPNAME,'-')-1) operationNumber
                                ,'Y' thisProcessProblem,'Y' batchQualityProblem,'Y' batchProcessPart,'Y' causedByRework,problemNature
                                ,fa.FACTORYNAME responsibleUnit,q.UNQUALIFIEDDESCRIBE problemDescription,ef.EMPLOYEENAME createEmployeeNo
                                ,DECODE(partCategory,'01','关键件','02','重要件','03','一般件','04','试验件','未知') partCategory ,p2.productrevision drawingRevision
                                FROM QUALITYHISTORYRECORD q 
                                LEFT JOIN FACTORY f ON f.FACTORYID=q.OrgFactoryID
                                LEFT JOIN USERATTRIBUTE u ON u.PARENTID =f.FACTORYID AND u.USERATTRIBUTENAME='分厂代码'
                                LEFT JOIN WORKCENTER w ON w.WORKCENTERID =q.WORKCENTERID
                                LEFT JOIN PRODUCTBASE p ON p.PRODUCTNAME =q.PRODUCTITEMNAME
                                LEFT JOIN PRODUCT p2 ON p2.PRODUCTBASEID =p.PRODUCTBASEID and p.revofrcdid=p2.productid 
                                LEFT JOIN WORKFLOWSTEP w2 ON w2.WORKFLOWSTEPID =q.WORKFLOWSTEPID
                                LEFT JOIN FACTORY fa ON fa.FACTORYID =q.FACTORYID
                                LEFT JOIN EMPLOYEE e ON e.EMPLOYEEID =q.CREATEEMPLOYEEID
                                LEFT JOIN (SELECT DISTINCT wfs.WORKFLOWID,e.CONTAINERNO,pf.PRODUCTFAMILYNAME FROM  enginepartplan e
                                	INNER JOIN workflowstep wfs ON e.workflowstepid=wfs.workflowstepid
                                	LEFT JOIN workflowproductfamilylist wff ON wfs.workflowid=wff.workflowid
				                	LEFT JOIN productfamily pf ON wff.productfamilylistid=pf.productfamilyid
                                ) wf1 ON wf1.CONTAINERNO=q.TOGETHERFLAG
                                LEFT JOIN (SELECT wm_concat(e.employeename) employeename,s.FACTORYID from roledef ro 
				                    left JOIN employeerole erl ON erl.roleid=ro.roleid
				                    left JOIN employee e on e.employeeid=erl.employeeid
				                    LEFT JOIN SESSIONVALUES s ON s.SESSIONVALUESID =e.SESSIONVALUESID 
				                    where ro.rolename like '%检验室主任' GROUP BY s.FACTORYID 
				                    ) ef ON ef.FACTORYID=q.OrgFactoryID
                                 left join WritetoOtherSystem ws on ws.parentid=q.qualityhistoryrecordid and ws.recordtype='QMS_qaProblemInfoReport'
                                WHERE nvl(q.status,0)=1 AND ws.parentid is null and rownum<500";
                DataSet myDS = OracleHelper.Query(strSql);  
                if (myDS == null)
                {
                    return null;
                }
                if (myDS.Tables.Count == 0)
                {
                    return null;
                }
                return myDS.Tables[0];
            }
            catch (Exception e)
            {
                LogHelp.WriteError("生产准备获取", e);
                return null;
            }
        }
        /// <summary>
        /// 获取Xml字典
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        private Dictionary<string, string> GetDictionary(DataRow row) {
            var strList = new Dictionary<string, string>();
            var keys = @"orderNo,dealName,productionUnit,masterModel,occurrencePlace,occurrenceDate,productName,drawingNo,productNum,occurrenceQuantity,mainUsedQuantity,outfieldUsedQuantity,economicLoss,impactConsequence,inspectionNo,workingHours,testRunType,engineNumber,problemOperation,operationNumber,drawingRevision,userCategory,partCategory,thisProcessProblem,batchQualityProblem,batchProcessPart,causedByRework,partFamily,accuracyClass,materialGrade,responsibleUnit,problemDescription,createEmployeeNo";
            foreach(var key in keys.Split(',')){
                if (row.Table.Columns.Contains(key))
                {
                    strList.Add(key, row[key].ToString());
                }else{
                 strList.Add(key,"");
                }
            }
            return strList;
        }
        
        /// <summary>
        /// 创建xml
        /// </summary>
        /// <param name="strList"></param>
        /// <returns></returns>
        private string CreateXMLForQualityMentionToQms(Dictionary<string, string> strList)
        {
            try
            {
                #region MyRegion
                XmlDocument doc = new XmlDocument();
                doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
                XmlNode ReqNode = doc.CreateElement("ReqMsg");
                XmlNode headerNode = doc.CreateElement("header");
                XmlNode senderNode = doc.CreateElement("sendSysName");
                senderNode.InnerText = "APP_MES";
                XmlNode rcvNode = doc.CreateElement("rcvSysName");
                rcvNode.InnerText = "APP_QMS";
                XmlNode extNode = doc.CreateElement("extConfig");
                extNode.AppendChild(doc.CreateElement("isReTry"));
                extNode.LastChild.InnerText = "false";
                extNode.AppendChild(doc.CreateElement("FunName"));
                extNode.LastChild.InnerText = "MES_Send_Service";
                headerNode.AppendChild(senderNode);
                headerNode.AppendChild(rcvNode);
                headerNode.AppendChild(extNode);
                ReqNode.AppendChild(headerNode);

                XmlNode root = doc.CreateElement("root");
                XmlNode qmsFun = doc.CreateElement("qmsFunName");
                qmsFun.InnerText = "qaProblemInfoReport";//具体调用方法
                root.AppendChild(qmsFun);

                XmlNode documentNode = doc.CreateElement("document");
                ReqNode.AppendChild(documentNode);

                XmlNode qmsDocument = doc.CreateElement("qmsDocument");//具体业务内容
                #endregion
                foreach (KeyValuePair<string, string> _key in strList)
                {
                    XmlNode mainData = doc.CreateElement(_key.Key);
                    mainData.InnerText = _key.Value;
                    qmsDocument.AppendChild(mainData);
                }
                root.AppendChild(qmsDocument);
                documentNode.AppendChild(doc.CreateCDataSection("<root>" + root.InnerXml + "</root>"));
                doc.AppendChild(ReqNode);
                return doc.InnerXml;
            }
            catch (Exception e)
            {
                LogHelp.WriteError("质量问题提起XML", e);
                return string.Empty;
            }
        }
        /// <summary>
        /// 发送成功，更新字段--IsSendErp（Null/0未推送,1已推送）
        /// </summary>
        private void UpdateQualityHistoryRecord(string orderNo,string dealName) {
            try {
                string updateSql = string.Format(@"UPDATE QualityhistoryRecord SET IsSendErp='1' WHERE MFGORDERNAME='{0}' AND DEALNAME='{1}'", orderNo, dealName);
                OracleHelper.ExecuteSql(updateSql);
            }catch(Exception ex){
                LogHelp.WriteLog("质量问题提起更新失败："+ex.Message);
            }
        }
    }
}
